﻿using Furion;
using Furion.DynamicApiController;
using Furion.RemoteRequest.Extensions;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;
using Mrhd.Core.Entities;
using Mrhd.Core.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Mrhd.Application
{
    /// <summary>
    /// 商品控制器
    /// </summary>
    [ApiDescriptionSettings("商品接口")]
    public class ProductAppService : IDynamicApiController
    {
        private readonly IProductService _service;
        private readonly IDistributedCache _distributedCache;
        private readonly ILogger<ProductAppService> _logger;
        public ProductAppService(IProductService service, IDistributedCache distributedCache, ILogger<ProductAppService> logger)
        {
            _service = service;
            _distributedCache = distributedCache;
            _logger = logger;
        }

        /// <summary>
        /// 获取商品类型列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<ProductTypeDto>> GetTypes()
        {
            var list = await _service.GetProductTypesAsync();
            var ww = list.Adapt<List<ProductTypeDto>>();
            return ww;
        }

        /// <summary>
        /// 获取指定商品类型的商品
        /// </summary>
        /// <param name="id">商品类型id</param>
        /// <param name="status">商品状态</param>
        /// <param name="key">搜索关键字</param>
        /// <param name="paging">分页信息</param>
        /// <returns></returns>
        public async Task<object> Get(int id, [FromQuery] int status, [FromQuery] string key, [FromQuery] PagingQuery paging)
        {
            var list = await _service.GetProductsAsync(id, status, key, paging);
            var data = list.Adapt<List<ProductEntityDto>>();
            return new { list = data, count = paging.RecordCount };
        }

        /// <summary>
        /// 更新商品类型
        /// </summary>
        /// <param name="types">商品类型列表</param>
        /// <returns></returns>
        public async Task<List<ProductTypeDto>> PutSaveTypes(List<ProductTypeDto> types)
        {
            var entities = types.Adapt<List<ProductTypeEntity>>();
            await _service.SaveProductTypeAsync(entities);
            var list = await _service.GetProductTypesAsync();
            return list.Adapt<List<ProductTypeDto>>();
        }

        /// <summary>
        /// 获取商品类型下最大的商品排序码
        /// </summary>
        /// <param name="id">商品类型id</param>
        /// <returns></returns>
        public async Task<int> GetSort(int id)
        {
            if (id == 0) return 0;
            return await _service.GetProductMaxSortAsync(id);
        }

        /// <summary>
        /// 创建商品
        /// </summary>
        /// <param name="product">商品实体</param>
        /// <returns></returns>
        public async Task<ProductEntityDto> Create(ProductEntityDto product)
        {
            var entity = product.Adapt<ProductEntity>();
            await UploadImagesAsync(entity);
            await _service.CreateProductAsync(entity);
            return entity.Adapt<ProductEntityDto>();
        }

        /// <summary>
        /// 更新商品
        /// </summary>
        /// <param name="product"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<ProductEntityDto> Update(ProductEntityDto product)
        {
            var entity = product.Adapt<ProductEntity>();
            await UploadImagesAsync(entity);
            entity = await _service.UpdateProductAsync(entity);
            return entity.Adapt<ProductEntityDto>();
        }

        /// <summary>
        /// 商品上架
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<string> PutUp(int id)
        {
            await _service.ChangeStatusAsync(id, ProductStatus.Sale);
            return "上架成功";
        }

        /// <summary>
        /// 商品下架
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<string> PutDown(int id)
        {
            await _service.ChangeStatusAsync(id, ProductStatus.NotSale);
            return "下架成功";
        }

        /// <summary>
        /// 删除商品
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<string> Delete(int id)
        {
            await _service.DeleteAsync(id);
            return "操作成功";
        }

        /// <summary>
        /// 批量上架
        /// </summary>
        /// <returns></returns>
        public async Task<string> PutUpBatch(List<int> ids)
        {
            await _service.ChangeStatusAsync(ids, ProductStatus.Sale);
            return "上架成功";
        }

        /// <summary>
        /// 批量下架
        /// </summary>
        /// <returns></returns>
        public async Task<string> PutDownBatch(List<int> ids)
        {
            await _service.ChangeStatusAsync(ids, ProductStatus.NotSale);
            return "下架成功";
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <returns></returns>
        public async Task<string> DeleteBatch(List<int> ids)
        {
            await _service.DeleteAsync(ids);
            return "删除成功";
        }





        


        /// <summary>
        /// 上传图片到文件服务器
        /// </summary>
        /// <param name="product"></param>
        /// <returns></returns>
        private async Task UploadImagesAsync(ProductEntity product)
        {
            if (product.Images == null || product.Images.Count == 0) return;
            var fileUrl = App.Configuration["FileSystem:Url"];
            var images = product.Images.Where(a => a.Id == 0).ForEach(a =>
            {
                a.Name = Guid.NewGuid().ToString().Replace("-", "").ToLower() + ".jpg";
            });
            if (images.Count() == 0) return;
            _logger.LogInformation($"上传附件数：{images.Count()}，文件服务器路径：{fileUrl}");
            var res = await $"{fileUrl}/api/product".SetBody(images).PostAsync();
            res.EnsureSuccessStatusCode();

        }



    }
}
